<template>
  <div style="border: 1px solid #ccc">
    <a-row class="top-container" type="flex" align="middle">
      <a-col flex="100px">
        <a-button type="text" @click="trigger('back')">
          <template #icon>
            <double-left-outlined/>
          </template>
          返回
        </a-button>
      </a-col>
      <a-col flex="auto" align="end">
        <a-button type="dashed" style="margin-right: 10px" @click="trigger('save')">保存草稿</a-button>
        <a-button type="primary" @click="trigger('submit')">发布文章</a-button>
      </a-col>
    </a-row>
    <div style="border-bottom: 1px solid #e8e8e8;">
      <Toolbar
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
          class="editor-toolbar"
      />
    </div>
    <div class="main-container">
      <div class="editor-container">
        <div class="title-container">
          <input v-model="inTitle" placeholder="文章标题...">
        </div>
        <Editor
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            class="editor-text-area"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onBeforeUnmount, shallowRef, onMounted, computed, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { upload } from '@/api/file'

export default {
  components: { Editor, Toolbar },
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
  },
  setup(props, { emit }) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    const valueHtml = computed({
      get() {
        return props.modelValue
      },
      set() {
        emit('update:modelValue', editorRef.value.getHtml())
      }
    })
    const inTitle = computed({
      get() {
        return props.title
      },
      set(e) {
        emit('update:title', e)
      }
    })

    const toolbarConfig = {
      excludeKeys: 'fullScreen',
      fontSize: '15px'
    }

    const editorConfig = {
      placeholder: 'Type here...',
      scroll: false, // 禁止编辑器滚动
      MENU_CONF: {
        uploadImage: {
          async customUpload(file, insertFn) {
            console.log(file)           // JS 语法
            const { data, status } = await upload({
              files: file
            })
            if (status != 300) return
            console.log(data)
            // file 即选中的文件
            // 自己实现上传，并得到图片 url alt href
            // 最后插入图片
            insertFn(file.url, file.alt, file.href)
          },
          // 自定义插入图片
          customInsert(res, insertFn) {  // TS 语法
            console.log(res)
            // customInsert(res, insertFn) {                  // JS 语法
            // res 即服务端的返回结果

            // 从 res 中找到 url alt href ，然后插入图片
            insertFn(res.url, res.alt, res.href)
          },
        }
      }
    }

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    onMounted(() => {
      window.addEventListener('keydown', handleEvent)
    })

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      window.removeEventListener('keydown', handleEvent)
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleEvent = (event) => {
      switch (event.keyCode) {
        case 83:
          event.preventDefault()
          event.returnValue = false // 阻止直接保存网页
          // eslint-disable-next-line no-prototype-builtins
          if (event.ctrlKey && event.code === 'KeyS') {
            // 在这里写保存需要执行的逻辑
            emit('event', {
              type: 'save',
              value: editorRef.value.getHtml(),
              back: 0
            });
          }
          break
      }
    }

    const trigger = (type) => {
      emit('event', {
        type: type,
        value: editorRef.value.getHtml(),
        back: 1
      })
    }

    return {
      editorRef,
      inTitle,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,

      trigger,
    };
  }
}
</script>

<style lang="less" scoped>

.top-container {
  padding: 0 30px;
  height: 60px;
  border-bottom: 1px solid #e8e8e8;
}

.editor-toolbar {
  width: 1350px;
  margin: 0 auto;
  background-color: #FCFCFC;
}

.editor-text-area {
  min-height: 900px;
  margin-top: 20px;
}

.main-container {
  height: calc(100% - 40px);
  background-color: rgb(245, 245, 245);
  overflow-y: auto;
  position: relative;

  .editor-container {
    width: 850px;
    background-color: #fff;
    padding: 20px 50px 50px 50px;
    margin: 30px auto 150px auto;
    border: 1px solid #e8e8e8;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: content-box;

    :deep(#w-e-textarea-1) {
      min-height: 500px;
      //padding: 0;
    }
  }


  .title-container {
    padding: 20px 0;
    border-bottom: 1px solid #e8e8e8;
  }

  .title-container input {
    font-size: 30px;
    border: 0;
    outline: none;
    width: 100%;
    line-height: 1;
  }

  .editor-text-area {
    min-height: 900px;
    margin-top: 20px;
  }
}
</style>
